package cn.ltq.springbootplus.controller;

import cn.ltq.springbootplus.entity.Book;
import cn.ltq.springbootplus.service.IBookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    IBookService iBookService;

    @GetMapping
    public String books(Model model){
        List<Book>list=iBookService.list();
        model.addAttribute("list",list);
        return "books";
    }

    @PostMapping()
    public String searchBooks(Model model,Book book){
        List<Book>list=iBookService.searchBooks(book);
        model.addAttribute("list",list);
        return "books";
    }

    @GetMapping("/page")
    public String page(@RequestParam(defaultValue = "1") Integer pageNum, Model model){
       IPage page =iBookService.getPage(pageNum);
        model.addAttribute("page",page);
        return "booksPage";
    }

    @PostMapping("/add")
    public String add(Book book){
        book.setSales(0);
        iBookService.saveOrUpdate(book);
//        ModelAndView mv=new ModelAndView();
//        mv.setViewName("redirect:/book");
       return "booksadd";
    }

    @GetMapping("/del")
    public String del(@RequestBody Integer id){
        iBookService.removeById(id);
        return "books";
    }
}
